local ROT = require 'rot'

local state = ROT.Class:extend()

function state:center()
    local player = self.game.player
    local display = self.game.display
    self.offsetX = math.floor(player.x - display:getWidth() / 2)
    self.offsetY = math.floor(player.y - display:getHeight() / 2)
end

function state:init(game, play)
    self.game = game
    self.play = play
    self:center()
end

function state:update()
    local play = self.play
    local display = self.game.display
    local player = self.game.player
    local scene = self.game.scene
    display:clear()
    for x = 1, display:getWidth() do for y = 1, display:getHeight() do
        local tx, ty = x + self.offsetX, y + self.offsetY
        if scene.seen:getCell(tx, ty) then
            if tx == player.x and ty == player.y then
                display:write('@', x, y)
            else
                local t = scene:getTile(tx, ty)
                display:write(t.glyph or ' ', x, y, t.color, nil, true)
            end
        end
    end end
end

function state:keypressed(key)
    local game = self.game
    local newPos

    if     key==game.keys.move_nw then newPos={ -1, -1 }
    elseif key==game.keys.move_n then newPos={ 0, -1 }
    elseif key==game.keys.move_ne then newPos={ 1, -1 }
    elseif key==game.keys.move_w then newPos={ -1, 0 }
    elseif key==game.keys.rest then self:center()
    elseif key==game.keys.move_e then newPos={ 1, 0 }
    elseif key==game.keys.move_sw then newPos={ -1, 1 }
    elseif key==game.keys.move_s then newPos={ 0, 1 }
    elseif key==game.keys.move_se then newPos={ 1, 1 }
    elseif key==game.keys.map or '\27' then game:popState()
    end

    if newPos then
        self.offsetX = self.offsetX + newPos[1]
        self.offsetY = self.offsetY + newPos[2]
    end
end

return state
